/**
 * 表单校验规则
 */

/**
 * 判断url是否是http或https 
 * @param {string} path
 * @returns {Boolean}
 */
export function isHttp(url) {
  return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1
}

/**
 * 判断path是否为外链
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

/**
 * 校验用户名
 * @param {string} username
 * @returns {Boolean}
 */
export function validUsername(username) {
  const pattern = /^[a-zA-Z0-9]{3,20}$/
  return pattern.test(username)
}

/**
 * 校验blob响应内容
 * @param {Blob} data
 * @returns {Promise<Boolean>}
 */
export async function blobValidate(data) {
  try {
    const text = await data.text()
    const result = JSON.parse(text)
    return !(result && result.code && result.code !== 200)
  } catch (error) {
    return true
  }
}

/**
 * 校验邮箱
 * @param {string} email
 * @returns {Boolean}
 */
export function validEmail(email) {
  const pattern = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
  return pattern.test(email)
}

/**
 * 校验手机号
 * @param {string} phone
 * @returns {Boolean}
 */
export function validPhone(phone) {
  const pattern = /^1[3-9]\d{9}$/
  return pattern.test(phone)
}

/**
 * 校验身份证号
 * @param {string} idCard
 * @returns {Boolean}
 */
export function validIdCard(idCard) {
  const pattern = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  return pattern.test(idCard)
} 